package com.framework.common.utils;


import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component("springContextUtils")
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz) {
        return (T) applicationContext.getBean(clazz);
    }

    /**
     * 获取所有实现类
     */
    public static <T> List<T> getBeanListOfType(Class<T> clazz) {
        List result = new ArrayList<>();
        Map<String, T> map = applicationContext.getBeansOfType(clazz);
        if (null != map) {
            result.addAll(map.values());
        }
        return result;
    }

//    private static ApplicationContext applicationContext = null;
//
//    public static ApplicationContext getApplicationContext() {
//        return applicationContext;
//    }
//
//    @SuppressWarnings("unchecked")
//    public static <T> T getBean(String beanId) {
//        return (T) applicationContext.getBean(beanId);
//    }
//
//    public static <T> T getBean(Class<T> requiredType) {
//        return (T) applicationContext.getBean(requiredType);
//    }
//
//    /**
//     * Spring容器启动后，会把 applicationContext 给自动注入进来，然后我们把 applicationContext 赋值到静态变量中，方便后续拿到容器对象
//     *
//     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
//     */
//    @Override
//    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//        SpringContextUtils.applicationContext = applicationContext;
//    }
}
